# -*-coding:utf-8-*-

import json
from tornado.httpclient import HTTPClient, HTTPRequest
from tests import configs


# from tornado.httpclient import AsyncHTTPClient
# import pycurl
# AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")

def url_compose(path, query=None):
    if query is None:
        query = 'utest=1'
    else:
        query += '&utest=1'
    if 80 == configs.PORT:
        return '%s://%s/%s?%s' % (configs.PROTOCOL, configs.HOST, path, query)
    else:
        return '%s://%s:%d/%s?%s' % (configs.PROTOCOL, configs.HOST, configs.PORT, path, query)


def http_get(path, query=None, headers=None):
    # headers = {'User-Agent': 'curl/7.22.0 (x86_64-unknown-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4'}
    url = url_compose(path, query)
    http_request = HTTPRequest(url, headers=headers)
    http_client = HTTPClient()
    return http_client.fetch(http_request, raise_error=False)


def __http_method(method, path, body=None, query=None, headers=None):
    url = url_compose(path, query)
    if body is not None:
        body = json.dumps(body)
    http_request = HTTPRequest(url, method=method, body=body, headers=headers)
    http_client = HTTPClient()
    return http_client.fetch(http_request, raise_error=False)


def http_post(path, body=None, query=None, headers=None):
    return __http_method('POST', path, body, query, headers=headers)


def http_put(path, body=None, query=None, headers=None):
    return __http_method('PUT', path, body, query, headers=headers)


def http_delete(path, body=None, query=None, headers=None):
    return __http_method('DELETE', path, body, query, headers=headers)
